package com.gonsin.gview.common.controller;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.gonsin.base.GPageRequest;
import com.gonsin.base.GPageResult;
import com.gonsin.base.ResponseResult;
import com.gonsin.base.exceptions.MyException;
import com.gonsin.gview.common.auth.AuthCommon;
import com.gonsin.gview.common.auth.JwtConfig;
import com.gonsin.gview.common.auth.WebApi;
import com.gonsin.gview.common.bean.EdificeBean;
import com.gonsin.gview.common.bean.UserBean;
import com.gonsin.gview.common.po.UserBo;
import com.gonsin.gview.common.services.IUserService;
import com.gonsin.gview.common.utils.SessionKeys;
import com.gonsin.gview.logic.config.GViewMenuService;
import com.gonsin.gview.model.menu.GViewMenu;
import com.gonsin.i18n.logic.T;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;

@Api(tags = "账户相关接口")
@RestController
@RequestMapping
@Slf4j
public class UserController  {
    @Autowired
    private IUserService userService;

    @Autowired
    private JwtConfig jwtConfig;

    @ApiOperation("用户 - 查询时间")
    @GetMapping("/api/base/system/time")
    public Date logout() throws IOException {
        return new Date();
    }

    @WebApi(login = true)
    @ApiOperation("用户 - 登出")
    @GetMapping("/api/user/logout")
    public ResponseResult<Void> logout(@ApiIgnore HttpSession session) throws IOException {
        return ResponseResult.simpleResult();
    }

    @WebApi(login = true)
    @ApiOperation("用户 - 普通登录")
    @ResponseBody
    @RequestMapping(value = {
            "/api/user/handle_login",   // @deprecated 该接口自S10开始，不再使用
            "/api/user/login"
    },
            method = RequestMethod.POST)
    public ResponseResult<UserBo> login(
            @ApiParam(value = "账号", required = true) @RequestParam("username") String username,
            @ApiParam(value = "密码", required = true) @RequestParam("password") String pwd,
            @ApiIgnore HttpSession session) {
        UserBo userBo = userService.login(username, pwd);
        handleLoginSuccess(session, userBo);
        return ResponseResult.result(userBo);
    }


    private void handleLoginSuccess(HttpSession session, UserBo userBo) {

        Map<String, Object> payload = new HashMap<>();
        payload.put(AuthCommon.SESSION_ID, RandomStringUtils.random(32, true, true));
        payload.put(SessionKeys.USER_KEY, userBo.getUserKey());
        if(userBo.getEdificeKeys().size() == 1){
            payload.put(SessionKeys.EDIFICE_KEY, userBo.getEdificeKeys().get(0));
            userBo.setEdificeKey(userBo.getEdificeKeys().get(0));
        }
        payload.put(SessionKeys.EDIFICE_KEYS, userBo.getEdificeKeys());
        Algorithm algorithm = Algorithm.HMAC256(jwtConfig.getJwtSecret());
        long expiredTime = System.currentTimeMillis() + jwtConfig.getExpiredTime();
        String token = JWT.create()
                .withIssuer(AuthCommon.ISSUER)
                .withIssuedAt(new Date())
                .withPayload(payload)
                .withExpiresAt(new Date(expiredTime + 60000))
                .sign(algorithm);
        userBo.setToken(token);
    }


    // 资源接口


    /////// S10开始，菜单获取方式会改到gview中，不再手动修改，以下接口为了短期内兼容旧项目 ////////
    @Autowired
    private GViewMenuService menuService;

    @Deprecated
    @ApiIgnore
    @ApiOperationSupport(order = 22001)
    @ApiOperation("菜单 - 查询所有菜单")
    @ResponseBody
    @GetMapping("/api/permissions")
    public ResponseResult<List<GViewMenu>> findAllMenu(HttpServletRequest request) {
        return ResponseResult.result(menuService.getMenus(request));
    }


}
